<template>
  <el-dialog width="400" :title="dialogTitle" v-model="dialogVisible" modal @close="closeDialog" draggable
    :close-on-click-modal="false" :append-to-body="true">
    <el-form class="dialog-form" :model="formData" ref="vForm" label-position="right" label-width="80px" size="medium"
      @submit.native.prevent :rules="formRules">
      <el-form-item label="识别码" prop="brandCode">
        <el-input v-model="formData.brandCode" :disabled="type === 'edit'" placeholder="请输入识别码" link clearable />
      </el-form-item>
      <el-form-item label="品类类型" prop="brandType">
        <el-select v-model="formData.brandType" placeholder="请选择品类类型" class="full-width-input" clearable>
          <el-option v-for="(item, index) in brandTypeOptions" :key="index" :label="item.label" :value="item.value"
            :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="默认端口" prop="devicePort">
        <el-input v-model.number="formData.devicePort" placeholder="请输入默认端口"
          onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" clearable maxlength="5" />
      </el-form-item>
      <el-form-item label="默认账号" prop="loginName">
        <el-input v-model="formData.loginName" placeholder="请输入默认账号" link clearable />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="固定列" prop="fixedColUrl">
            <el-upload class="avatar-uploader" :data="{ path: 'mjj' }" :action="`${uploadURL}sys/image/uploadImage`"
              :show-file-list="false" :on-success="handleAvatarSuccessFix" :before-upload="beforeAvatarUpload">
              <el-image v-if="formData.fixedColUrl" :src="`${uploadURL}/mjj/${formData.fixedColUrl} `" class="avatar"
                fit="contain" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <span class="beCareful_text bottom20">*请上传小于2MB并且是PNG格式的图片</span>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移动列" prop="moveColUrl">
            <el-upload class="avatar-uploader" :data="{ path: 'mjj' }" :action="`${uploadURL}sys/image/uploadImage`"
              :show-file-list="false" :on-success="handleAvatarSuccessMove" :before-upload="beforeAvatarUpload">
              <el-image v-if="formData.moveColUrl" :src="`${uploadURL}/mjj/${formData.moveColUrl}`" class="avatar"
                fit="contain" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog" size="mini">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, update, getInfo } from '@/api/bas/brand'
import { getDictItems } from '@/api/sys/dict'
export default {
  name: 'dictionaryDialog',
  data() {
    return {
      type: '',
      dialogTitle: '',
      dialogVisible: false,
      formData: {},
      formDisabled: false,
      formRules: {
        brandCode: [{ required: true, message: '请输入识别码', trigger: 'blur' }],
        brandType: [{ required: true, message: '请选择品类类型', trigger: 'change' }],
        devicePort: [{ required: true, message: '请输入默认端口', trigger: 'blur' }],
      },
      brandTypeOptions: [],
    }
  },
  created() {
    this.getBrandType()
  },
  methods: {
    // 上传成功回调
    // 固定列的上传成功回调
    handleAvatarSuccessFix(res, file) {
      if (res.code == 200) {
        this.formData.fixedColUrl = res.data
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    // 移动列的上传成功回调
    handleAvatarSuccessMove(res, file) {
      if (res.code == 200) {
        this.formData.moveColUrl = res.data
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    // 上传文件限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    getBrandType() {
      getDictItems('brand_type').then((res) => {
        if (res.data.code === 200) {
          this.brandTypeOptions = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    add() {
      this.formDisabled = false
      this.type = 'add'
      this.dialogTitle = '新增型号'
      // 先清空表单数据
      this.formData = {}
      this.dialogVisible = true
    },
    edit(row) {
      this.formDisabled = true
      this.type = 'edit'
      this.dialogTitle = '编辑型号'
      getInfo(row.brandId)
        .then((res) => {
          if (res.data.code === 200) {
            this.formData = res.data.data
            this.formData.brandType = this.formData.brandType.toString()
            this.dialogVisible = true
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    submitForm() {
      this.$refs['vForm'].validate((valid) => {
        if (valid) {
          if (this.type === 'add') {
            add(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('新增成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          } else {
            update(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('编辑成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          }
        }
      })
    },
    closeDialog() {
      this.$refs['vForm'].resetFields()
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped lang="less">
.dialog-form {
  padding: 0 30px;
  /* 根据需求调整数值 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
